<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\Project;
use app\index\model\Order as Orders;
use app\index\model\Member;
use app\index\model\OrderProfit;
use app\index\model\Putlog;
use app\index\model\Contract;
use app\index\model\OrderContract;
use app\firm\model\ProjectUser;
use app\index\model\Lookinto;

use expand\BestSignDemo;
use expand\Yunst;
use expand\YunPay;

class Order extends Common
{	
	public $oModel;
	public $ocModel;
	public $userId;
	
    public function _initialize(){
        parent::_initialize();
		if(!CheckMemberLogin()){
			return ajaxReturn('登录已过期');
		}
		$this->userId = session('UID');
		$this->oModel = new Orders;
		$this->ocModel = new OrderContract;
    }
    //添加支持订单
    public function create($id){
        if(request()->isAjax()){
            $lookModel = new Lookinto();
            $isLookInto = $lookModel->where(['uid'=>session('UID')])->field('create_time,score')->order('create_time desc')->limit(1)->find();
            $isLookInto = empty($isLookInto) ? array() : $isLookInto->toArray();
            if(empty($isLookInto) || ($isLookInto['score'] < LOOK_INTO_SORE)){
              ajaxReturn('您的投资类型评估不符合条件，请前往个人中心重新评估。',url('Member/lookinto'));
            }
            $money = input('post.money');
            $money = sprintf("%.2f",$money);
            if($money==0 || substr($money, 0, 1 )==0){
                return ajaxReturn('请输入正确的大于0的整数');
            }
            if(($money%100)!=0){
                return ajaxReturn('请输入100的整数倍');
            }

            $mModel = new Member();
            $pModel = new Project();
            $oModel = new \app\index\model\Order();
            $opModel = new OrderProfit();
            $puModel = new ProjectUser();
            $nowTime = time();
            $selfmoney = $mModel->where(['id'=>$this->userId])->value('money');
            $isCheck = $mModel->where(['id'=>$this->userId])->value('is_check');
            $parentId = $mModel->where(['id'=>$this->userId])->value('parentId');
            $subordinate_name = $mModel->where(['id'=>$this->userId])->value('username');
			if(!$isCheck){
				return ajaxReturn('请先进行实名认证');
			}
            if($money > $selfmoney){
                return ajaxReturn('账户余额不足');
            }

            $res=$pModel->where(['id'=>$id])->find()->toArray();
            $zuida=$res['target_code'];
            $min=$res['min_code'];
            $max=$res['max_code'];
//            if($money<$min){
//                return ajaxReturn('投资低于最低投资金额');
//            }
            if($money>$max){
                return ajaxReturn('投资大于最高投资金额');
            }
            $res=$oModel->where(['project_id'=>$id,'status'=>'1'])->select();
            $res=json_encode($res);
            $res=json_decode($res,true);
            $mo=0;
            foreach ($res as $v){
                $mo+=$v['money'];
            }
            $yue=$zuida-$mo;
            if($money>$yue){
                return ajaxReturn('投资大于剩余投资金额');
            }
            $ProInfo = $pModel->where(['id'=>$id])->find();
            $hasMoney = GetProjectBar($id);
            $overMoney = $ProInfo['target_code'] - $hasMoney;
            $overMoney = sprintf("%.2f",$overMoney);
            if($money > $overMoney){
                return ajaxReturn('最多可支持金额'.$overMoney.'元');
            }
            if($nowTime > $ProInfo['end_time']){
                return ajaxReturn('时间已结束');
            }
            if($ProInfo['end_time'] == -1){
                return ajaxReturn('项目已失败');
            }

            //创建支持订单
            $order = [
                'order_sn' => 'HRY'.create_order(),
                'uid' => $this->userId,
                'project_id' => $id,
                'money'	=> $money,
                'status' => 0,
                'type'=>1,
                'create_time'=> $nowTime
            ];
            //临时调整项目为不需要计算业绩以及佣金
//            if ($id == 28 || $id == 31 || $id==45) {
//                $order['transport'] = 1;
//            }
            if($ProInfo['is_count'] == 2){
                $order['transport'] = 1;
            }
            $order_id = $this->oModel->insertGetId($order);
            if(!$order_id){
                return ajaxReturn($this->oModel->getError());
            }

            //订单代收
            $YunClass = new Yunst();

            $bizUserId = $mModel->where(['id'=>$this->userId])->value('bizUserId');
            $project_info = $pModel->where(['id'=>$id])->find();
            $pu_info = $puModel->where(['id'=>$project_info['initiator']])->find();
            $message = $YunClass->DanBiDaiShou($bizUserId,$pu_info['bizUserId'],$order);
            if($message['status'] != 'OK'){
                return ajaxReturn($message['message']);
            } else {
                if ($parentId && $ProInfo['commission_proportion']) {
                    $member_name = $mModel->where(['id'=>$parentId])->value('username');
                    $member_mobile = $mModel->where(['id'=>$parentId])->value('mobile');
                    $subordinate_order = [];
                    $subordinate_order['project_id'] = $id;
                    $subordinate_order['order_sn'] = $order['order_sn'];
                    $subordinate_order['payment_sn'] = 'HRY'.create_order();
                    $subordinate_order['member_id'] = $parentId;
                    $subordinate_order['member_name'] = $member_name;
                    $subordinate_order['member_mobile'] = $member_mobile;
                    $subordinate_order['subordinate_member_id'] = $this->userId;
                    $subordinate_order['subordinate_name'] = $subordinate_name;
                    $subordinate_order['order_money'] = $money;
                    $subordinate_order['money'] = $money * ($ProInfo['commission_proportion'] / 100);
                    $subordinate_order['create_time'] = time();
                    $order_profit_id = $opModel->insertGetId($subordinate_order);
                }
            }
            $signedValue = json_decode($message['signedValue'],true);
            return ajaxReturn('即将跳转',url('Order/confirm',['id'=>$order_id]));
        }
    }
	//确定支付
    public function confirm($id){
	if(request()->isAjax()){
            $pModel = new Project();
            $data = $this->oModel->where(['id'=>$id,'uid'=>$this->userId])->find();
            $money=floatval($data['money']);
            $code = input('post.code');
            $proid=$data['project_id'];
            $pro=$pModel->where(['id'=>$proid])->find()->toArray();
            $status=$pro['status'];
            if($status==3){
                return ajaxReturn('该项目已经成功,敬请期待下个项目');
            }
            $summoney=$this->oModel->where(['status'=>2,'type'=>1,'project_id'=>$proid])->sum('money');
            $sum=($money+$summoney);
            $maxmoney=floatval($pro['target_code']);
            $sum=intval(($sum*100));
            $maxmoney=intval(($maxmoney*100));
            if($sum>$maxmoney){
                return ajaxReturn('本次投资金额超过剩余可投金额');
            }
            $payClass = new Yunst();
            $mModel = new Member();
            $bizUserId = $mModel->where(['id'=>$this->userId])->value('bizUserId');
            $res = $payClass->balancePay($bizUserId,$data['order_sn'],$code);
            if($res['status'] != 'OK'){
                return ajaxReturn($res['message']);
            }
			//生成合同记录
			//$this->makeContract($data['project_id'],$id,$data['money']);
			return ajaxReturn('支付成功',url('Project/detail',['id'=>$data['project_id']]));
		}else{
			$data = $this->oModel->where(['id'=>$id,'uid'=>$this->userId])->find();
			$mModel = new Member();
			$mobile = $mModel->where(['id'=>$this->userId])->value('mobile');
			$this->assign('data',$data);
			$this->assign('mobile',$mobile);
			return $this->fetch();
		}
	}
	
	//生成合同
	private function makeContract($id,$order_id,$money){
		$cotModel = new Contract();
		$ConList = $cotModel->where(['status'=>1,'project_id'=>$id])->select();
		if(empty($ConList)){
			return false;
		}
		foreach($ConList as $v){
			$ocontract = [
				'project_id' => $id,
				'cid' => $v['id'],
				'money' => $money,
				'user_id'	=> $this->userId,
				'title'	=> $v['title'],
				'order_id' => $order_id,
				'create_time' => date('Y-m-d H:i:s')
			];
			$id = $this->ocModel->insertGetId($ocontract);

			$contractId = $this->AddYuansu($id);
			$this->ocModel->where(['id'=>$id])->update(['contract_id'=>$contractId]);
		}
		return true;
	}
	//查看合同
	public function Seecontract($id)
	{

		$Best_data = new BestSignDemo();

		$where = ['id'=>$id,'user_id'=>$this->userId];
		$ContInfo = $this->ocModel->where($where)->find();

		if(empty($ContInfo['contract_id'])){
			$contractId = $this->AddYuansu($id);
			if(empty($contractId)){
				return ajaxReturn('合同信息错误');
			}
			$this->ocModel->where($where)->update(['contract_id'=>$contractId]);
		}

        //$this->signContract($id);
        $ssqmobile=$ContInfo->ssqaccount;

		$result = $Best_data->viewContract($ContInfo['contract_id']?$ContInfo['contract_id']:$contractId,$ssqmobile);

		if($result->errno == 0){
			return ajaxReturn('获取成功',$result->data->url);
		}else{
			return ajaxReturn($result->errmsg);
		}
	}
	
	//签署合同
	public function signContract($id){
		$Best_data = new BestSignDemo();
		$cotModel = new Contract();
		$mModel = new Member();
		$ContInfo = $this->ocModel->where(['user_id'=>$this->userId,'id'=>$id])->find();
		if(empty($ContInfo)){
			return ajaxReturn('合同信息错误');
		}
		if(empty($ContInfo['contract_id'])){
			return ajaxReturn('请先查看合同后再来签署哦');
		}
		$Cinfo = $cotModel->where(['id'=>$ContInfo['cid']])->find();
		if($ContInfo['sign']!=0){
			return ajaxReturn('此状态无法进行合同签署');
		}
		$ssqlmobile = $mModel->where(['id'=>$this->userId])->value('ssqlmobile');
		$position = [[
			'pageNum' => $Cinfo['dpage'],
			'x' => $Cinfo['dxname'],
			'y' => $Cinfo['dyname']
		]];
		$result = $Best_data->signContract($ContInfo['contract_id'],$ssqlmobile,$position);
		if($result['errno'] == 0){
			$this->ocModel->where(['id'=>$id])->update(['sign'=>1,'date'=>date('Y-m-d H:i:s'),'ssqaccount'=>$Cinfo['account']]);
			TobeNotice('合同通知','合同签署成功【'.$ContInfo['title'].'】');
			return ajaxReturn('签署成功',url('Member/contract'));
		}else{
			return ajaxReturn($result['errmsg']);
		}
	}
	//下载合同
	public function DownContract($id){
		$ocinfo = $this->ocModel->where(['id'=>$id])->find();
		if(empty($ocinfo)){
			return ajaxReturn('合同信息错误');
		}
		if(empty($ocinfo['contract_id'])){
			return ajaxReturn('请先查看合同后再来下载');
		}
		$Best_data = new BestSignDemo();
		$res = $Best_data->downloadContract($ocinfo['contract_id']);
		return ajaxReturn('OK',$res);
	}
	
	//合同添加元素
	private function AddYuansu($id){
		$cotModel = new Contract();
		$mModel = new Member();
		$Best_data = new BestSignDemo();
		$where = ['id'=>$id,'user_id'=>$this->userId];
		$OCinfo = $this->ocModel->where($where)->find();
		$Cinfo = $cotModel->where(['id'=>$OCinfo['cid']])->find();
		$MemberInfo = $mModel->where(['id'=>$this->userId])->find();
		//姓名
		$ADDdata[] = $Best_data->writeContent($Cinfo['npage'],$Cinfo['xname'],$Cinfo['yname'],$MemberInfo['username']);
		//身份证
		$ADDdata[] = $Best_data->writeContent($Cinfo['id_card'],$Cinfo['xcard'],$Cinfo['ycard'],$MemberInfo['certificate']);
		//金额
		$ADDdata[] = $Best_data->writeContent($Cinfo['mpage'],$Cinfo['xmoney'],$Cinfo['ymoney'],$OCinfo['money']);
		//大写金额
		$ADDdata[] = $Best_data->writeContent($Cinfo['hz_page'],$Cinfo['hz_x'],$Cinfo['hz_y'],num_to_rmb($OCinfo['money']));
        //金额2
        $ADDdata[] = $Best_data->writeContent($Cinfo['mtopage'],$Cinfo['xtomoney'],$Cinfo['ytomoney'],$OCinfo['money']);
        //大写金额2
        $ADDdata[] = $Best_data->writeContent($Cinfo['hzto_page'],$Cinfo['hzto_x'],$Cinfo['hzto_y'],num_to_rmb($OCinfo['money']));
		$res = $Best_data->putContent($Cinfo['fid'],$ADDdata);
		$contractId = $Best_data->create($res->data->fid,$Cinfo['title'],$Cinfo['expiretime']);
		return $contractId;
	}

	public function saveprofit(){
        $orderModel =  new Orders();
        $orderProfitModel = new OrderProfit();
        $memberModel = new Member();
        $start_date = '2018-11-14 00:00:01';
        $end_date = '2018-12-8 12:14:00';
        $where['project_id'] = ['in',[19,25]];
        $where['create_time'] = ['between time', [strtotime($start_date),strtotime($end_date)]];
        $where['status'] = 2;
        $where['type'] = 1;
        $data = $orderModel->where($where)->select();
        $new_data = [];
        $aaa = 0;
        $ccc = 0;
        foreach ($data as $key=>$val) {
            $memberData = $memberModel->where(['id'=>$val['uid']])->find();
            $newMemberData = $memberModel->where(['id'=>$memberData['parentId']])->find();
            if ($newMemberData) {
                $new_data[$key]['member_id'] = $newMemberData['id'];
                $new_data[$key]['project_id'] = $val['project_id'];
                $new_data[$key]['payment_sn'] = 'HRY'.create_order();
                $new_data[$key]['member_name'] = $newMemberData['username'];
                $new_data[$key]['member_mobile'] = $newMemberData['mobile'];
                $new_data[$key]['subordinate_member_id'] = $memberData['id'];
                $new_data[$key]['subordinate_name'] = $memberData['username'];
                $new_data[$key]['order_money'] = $val['money'];
                $new_data[$key]['money'] = $val['money'] * 0.06;
                $new_data[$key]['status'] = 0;
                $new_data[$key]['create_time'] = time();
                $new_data[$key]['order_sn'] = $val['order_sn'];
                $aaa += $val['money'] * 0.06;
            } else {
                $ccc +=$val['money'] * 0.06;
            }
        }
        echo $aaa.'-------';
        echo $ccc;exit;
        $orderProfitModel->insertAll($new_data);
        //echo '<pre/>';print_r($new_data);exit;
        echo $aaa.'-------';
        echo count($new_data);exit;

    }
}
